package com.zwt.util.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HttpRequest {

    private static final String DEFAULT_URL = "http://980.so/api.php";

    private static final String BACKUP_URL = "http://goo.gd/action/json.php";


    /**
     * 向指定URL发�?�GET方法的请�?
     *
     * @param url   发�?�请求的URL
     * @param map 请求参数，请求参数应该是 name1=value1&name2=value2 的形式�??
     * @return URL �?代表远程资源的响应结�?
     */
	public static String sendGetMap(String url, Map<String, Object> map) {
		StringBuffer params = new StringBuffer();
		if(map != null){
			Iterator<Entry<String, Object>> it = map.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, Object> element = (Entry<String, Object>) it.next();
				params.append(element.getKey());
				params.append("=");
                try {
                    params.append(URLEncoder.encode(""+ element.getValue(),"UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                params.append("&");
			}
		}
		return sendGet(url,params.toString());
	}
	
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            param = StringUtils.isEmpty(param) ? "" : ("?" + param);
            String urlNameString = url + param;
            URL realUrl = new URL(urlNameString);

            // 打开和URL之间的连�?
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属�?
            connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
            connection.setRequestProperty("Cache-Control", "no-cache");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Host", "api.xunjia.yunfangdata.com");
            connection.setRequestProperty("Upgrade-Insecure-Requests", "1");

            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36");
            // 建立实际的连�?
            connection.connect();




            // 定义 BufferedReader输入流来读取URL的响�?
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(String.format("http get error, url:%s, parmas:%s", url, param), e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {}
        }
        return result;
    }

    public static void main(String[] aa){
//    	Map<String,String> map = JSON.parseObject();

//    	String url = "http://distspace.cloundcai.com/cinema/home.htm";

        String url = "http://distspace.cloundcai.com/cinema/home.htm";

//    	StringBuffer params = new StringBuffer();
//		System.out.println(params.toString());
    	System.out.println(sendPost("https://fapiao.yonyoucloud.com/yesfp-einvoice-ops/api/base/testconnection?appid=commontesterCA",null));
    	
//    	System.out.println("-------->"+sendPost("http://980.so/api.php","?url="+url));
//    	try {
//			System.out.println("-------->"+getShortUrl(url));
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

    }

    /**
     * 向指�? URL 发�?�POST方法的请�?
     *
     * @param url   发�?�请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式�??
     * @return �?代表远程资源的响应结�?
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连�?
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属�?
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发�?�POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发�?�请求参�?
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响�?
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
        	throw new RuntimeException(String.format("http post error, url:%s, parmas:%s", url, param), e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {}
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static String postUrlJosn(String path,String jsonStr){
        Map<String, String> mapParam = JSON.parseObject(jsonStr, Map.class);
        return postUrl(path,mapParam);
    }
    /**
     * POST请求获取数据
     */
    public static String postUrl(String path,Map<String, String> map){
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流

            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("contentType", "utf-8");

            OutputStreamWriter printWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "utf-8");

//            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            StringBuffer params = new StringBuffer();
            Iterator<Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, String> element = (Entry<String, String>) it.next();
                params.append(element.getKey());
                params.append("=");
                params.append(element.getValue());
                params.append("&");
            }


            // 发送请求参数
            printWriter.write(params.toString());//post的参数 xx=xx&yy=yy
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while((len=bis.read(arr))!= -1){
                bos.write(arr,0,len);
                bos.flush();
            }
            bos.close();
            return bos.toString("utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    } 
	

	/**
	 * 把长连接转换成短连接
	 * @param longUrl
	 * @return
	 * @throws Exception
	 */
	public static String getShortUrl(final String longUrl) throws Exception {
		Map<String, Object> params = new HashMap<>();
		
		params.put("url", longUrl);
		String resultStr = sendGetMap(DEFAULT_URL, params);
		
		if(!StringUtils.isEmpty(resultStr)) {
            return resultStr;
        }
		
		//调用第一个服务http://980.so/api.php转短连接失败，继续下一个
		params.clear();
		
		params.put("source", "1681459862");
		params.put("url_long", longUrl);
		resultStr = sendGetMap(BACKUP_URL, params);
		
		if(!StringUtils.isEmpty(resultStr)){
			JSONObject result = JSONObject.parseObject(resultStr);
			if(!StringUtils.isEmpty(result.getJSONArray("urls")) && result.getJSONArray("urls").size() > 0
					&& !StringUtils.isEmpty(result.getJSONArray("urls").getJSONObject(0))
					&& !StringUtils.isEmpty(result.getJSONArray("urls").getJSONObject(0).get("url_short"))){
				return result.getJSONArray("urls").getJSONObject(0).getString("url_short");
			}
		}
		return null;
    }


    private static String initUrl(HttpServletRequest request) {
        String url;
        url = request.getScheme() + "://" + request.getServerName();
        if (request.getServerPort() != 80) {
            url += ":" + request.getServerPort();
        }
        url += request.getServletPath();
        if (request.getQueryString() != null) {
            url += "?" + request.getQueryString();
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(url)) {
            return url;
        }
        return null;
    }
    /**
     * 扩展初始化url方法
     * @param request
     * @param isEncoded
     * @return
     * @throws Exception
     */
    public static String initRedirectURL(final HttpServletRequest request, final Boolean isEncoded) throws Exception {
        final String ENC = "UTF-8";
        String initUrl = initUrl(request);
        if (org.apache.commons.lang.StringUtils.isEmpty(initUrl)) {
            throw new NullPointerException("init Url is Null");
        }
        if (isEncoded) {
            return URLEncoder.encode(initUrl, ENC);
        }
        return initUrl;
    }

}